<?php

namespace App\Http\Controllers;

use Auth;
use App\Models\User;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\User\CreateForm;
use App\Http\Requests\User\UpdateForm;
use App\Http\Requests\User\UploadAvatarForm;
use Illuminate\Foundation\Auth\RegistersUsers;
use App\Http\Requests\User\UpdatePasswordForm;

class UserController extends Controller
{

    use RegistersUsers;

    /**
     * @var string
     */
    protected $redirectTo = '/index';

    /**
     * @var User
     */
    protected $user;
    protected $permission;

    /**
     * UserController constructor.
     * @param User $user
     */
    public function __construct(User $user,Permission $permission)
    {
        $this->user = $user;
        $this->permission = $permission;
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(){

        $this->validateUserPermissionRedirect('show-users');
        $users = $this->user->getAllList();

        return view('user.index',compact('users'));

    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create(){

        $this->validateUserPermissionRedirect('create-user');

        $roles = Role::all();

        return view('user.create',compact('roles'));

    }

    /**
     * @param CreateForm $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(CreateForm $request){

        $this->validateUserPermissionRedirect('create-user');
        $this->user->name = $request->name;
        $this->user->email = $request->email;
        $this->user->password = bcrypt($request->password);
        $this->user->avatar = '/storage/avatars/2017/11/19/6gxMoMWOQsRvWJLdqvfQo35UHhdfMo0HDWR0vxXA.png';
        $this->user->cn_nickname = $request->cn_nickname;
        $this->user->en_nickname = $request->en_nickname;
        $this->user->mobile_phone = $request->mobile_phone;
        $this->user->qq_no = $request->qq_no;
        $this->user->save();

        session()->flash('success','添加用户 '.$request->name.' 成功');
        return  redirect()->route('user.index');
    }

    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit( $id ){

        if($this->validateUserPermission('show-user') || $this->validateUserPermission('edit-user')){
            $data = [];
            $user = $this->user->find($id);
            $data = compact('user');
            if($this->validateUserPermission('show-user-roles') || $this->validateUserPermission('edit-user-roles')){
                $roles = Role::all();
                $permissionGroup = $this->permission->getPermissionGroups();
                $data = compact('user','roles','permissionGroup');
            }
            return view('user.edit',$data);
        }
        abort(404);

    }

    /**
     *
     * @param UpdateForm $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(UpdateForm $request,$id){

        $this->validateUserPermissionRedirect('edit-user');
        DB::beginTransaction();
        try{
            $user = $this->user->find($id);
            $user->name = $request->name;
            $user->email = $request->email;
            $user->save();

            if($this->validateUserPermission('edit-user-roles')){
                if($request->roles){
                    $user->syncRoles($request->roles);
                }else{
                    $userRoles = $user->roles->pluck('name')->all();
                    foreach ($userRoles as $role){
                        $user->removeRole($role);
                    }
                }
                if($request->permissions){
                    $user->syncPermissions($request->permissions);
                }else{
                    $userPermissions = $user->permissions->pluck('name')->all();
                    foreach ($userPermissions as $userPermission){
                        $user->revokePermissionTo($userPermission);
                    }
                }

            }

            DB::commit();
            session()->flash('success','修改成功');
            return  redirect()->route('user.index');
        }catch (\Exception $exception){
            DB::rollBack();
            session()->flash('danger','修改失败，请稍后再试！');
            return  redirect()->back();
        }

    }

    public function profile(){
        return view('user.profile');
    }

    public function editAvatar(UploadAvatarForm $request){

        $user = Auth::user();

        $user->avatar = $request->avatar;

        if($user->save()){
            session()->flash('success','修改成功');
            return  redirect()->route('profile');
        }
        session()->flash('danger','修改失败，请稍后再试！');
        return  redirect()->back();
    }

    public function updatePassword(UpdatePasswordForm $request){
        $this->validateUserPermissionRedirect('update-user-password');
        $user = Auth::user();

        if(Hash::check($request->old_password,$user->password)){
            $user->password = bcrypt($request->password);

            if($user->save()){
                session()->flash('success','修改成功');
                return  redirect()->route('profile');
            }
            session()->flash('danger','修改失败，请稍后再试！');
            return  redirect()->back();
        }

        session()->flash('danger','原密码错误');
        return  redirect()->back();
    }

    public function editPasswordById($id){
        $user = $this->user->find($id);
        if(!$user){
            abort(404);
        }
        return view('user.password',compact('user'));
    }

    public function updatePasswordById(Request $request,$id){

        $this->validate($request, [
            'password'=>['required','min:8','confirmed'],
        ]);

        $user = $this->user->find($id);
        $user->password = bcrypt($request->password);
        if($user->save()){
            session()->flash('success','修改成功');
            return  redirect()->route('user.index');
        }
        session()->flash('danger','修改失败，请稍后再试！');
        return  redirect()->back();

    }


}
